package com.baoming.util;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServiceTool {
	
	/**
	 * 设置cookie
	 * @param response
	 * @param name  cookie名字
	 * @param value cookie值
	 * @param maxAge cookie生命周期  以秒为单位
	 */
	public static void addCookie(HttpServletResponse response,String name,String value,int maxAge){
	    Cookie cookie = new Cookie(name,value);
	    cookie.setPath("/");
	    if(maxAge>0)  cookie.setMaxAge(maxAge);
	    response.addCookie(cookie);
	}
	
	/**
	 * 根据名字获取cookie
	 * @param request
	 * @param name cookie名字
	 * @return
	 */
	public static Cookie getCookieByName(HttpServletRequest request,String name){
	    Map<String,Cookie> cookieMap = ReadCookieMap(request);
	    if(cookieMap.containsKey(name)){
	        Cookie cookie = (Cookie)cookieMap.get(name);
	        return cookie;
	    }else{
	        return null;
	    }   
	}
	
	/**
	 * 将cookie封装到Map里面
	 * @param request
	 * @return
	 */
	private static Map<String,Cookie> ReadCookieMap(HttpServletRequest request){  
	    Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
	    Cookie[] cookies = request.getCookies();
	    if(null!=cookies){
	        for(Cookie cookie : cookies){
	            cookieMap.put(cookie.getName(), cookie);
	        }
	    }
	    return cookieMap;
	}

	/**
	 * ISO-8859-1 转码成为 utf-8
	 * @param str
	 * @return
	 */
	public static String iosToUtf8(String str){
		String result = null;
		try {
			result = new String(str.getBytes("iso-8859-1") , "utf-8");
		} catch (UnsupportedEncodingException e) { 
			e.printStackTrace();
		} 
		return result ; 
	}
	
	public static final int DESCRIPTION_LENTH = 120 ; 
	  
	public static String subStringHTML(String param, int length, String end) {
		StringBuffer result = new StringBuffer();
		int n = 0;
		char temp;
		boolean isCode = false; 
		boolean isHTML = false;  
		for (int i = 0; i < param.length(); i++) {
			temp = param.charAt(i);
			if (temp == '<') {
				isCode = true;
			} else if (temp == '&') {
				isHTML = true;
			} else if (temp == '>' && isCode) {
				n = n - 1;
				isCode = false;
			} else if (temp == ';' && isHTML) {
				isHTML = false;
			}
			if (!isCode && !isHTML) {
				n = n + 1;
				if ((temp + "").getBytes().length > 1) {
					n = n + 1;
				}
			}
			result.append(temp);
			if (n >= length) {
				break;
			}
		}
		result.append(end);
		String temp_result = result.toString().replaceAll("(>)[^<>]*(<?)",
				"$1$2");
		temp_result = temp_result
				.replaceAll(
						"</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>",
						"");
		temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>",
				"$2");
		Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>");
		Matcher m = p.matcher(temp_result);
		List<String> endHTML = new ArrayList<String>();
		while (m.find()) {
			endHTML.add(m.group(1));
		}
		for (int i = endHTML.size() - 1; i >= 0; i--) {
			result.append("</");
			result.append(endHTML.get(i));
			result.append(">");
		}
		return result.toString();
	}
	
 
	public static String getNowDate() {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(new java.util.Date());
		return dateString;
	}

	
	/**
	 * html 2 text
	 * @param inputString
	 * @param length
	 * @return
	 */
	public static String html2Text(String inputString, int length) {
		String htmlStr = inputString;  
		String textStr = "";
		java.util.regex.Pattern p_script;
		java.util.regex.Matcher m_script;
		java.util.regex.Pattern p_style;
		java.util.regex.Matcher m_style;
		java.util.regex.Pattern p_html;
		java.util.regex.Matcher m_html;

		try {
			String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";  
			String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; 
			String regEx_html = "<[^>]+>";  

			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll("");  

			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll("");  

			p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll("");  

			textStr = htmlStr;

		} catch (Exception e) {
			System.err.println("Html2Text: " + e.getMessage());
		}

		return textStr.substring(0, length >= textStr.length() ? textStr
				.length() : length); 
	}
	 
	public static int timeCompain(String str1, String str2){
		 DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		 try {
			 Date one; 
			 Date two;  
			 one = df.parse(str1); 
			 two = df.parse(str2); 
			 long time1 = one.getTime(); 
			 long time2 = two.getTime();  
			 if(time1 > time2) { 
			     return 1 ; 
			 }else if(time1 == time2){
				return -1 ; 
			 } else { 
			     return 0 ; 
			 }
		} catch (ParseException e) { 
			e.printStackTrace();
		} 
		return 0 ; 
	}
	  
	public static MyDate getDistanceTime(String str1, String str2) { 
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        MyDate mydate = new MyDate() ;
        Date one; 
        Date two; 
        long day = 0; 
        long hour = 0; 
        long min = 0; 
        long sec = 0; 
        try { 
            one = df.parse(str1); 
            two = df.parse(str2); 
            long time1 = one.getTime(); 
            long time2 = two.getTime(); 
            long diff ; 
            if(time1<time2) { 
                diff = time2 - time1; 
            } else { 
                diff = time1 - time2; 
            } 
            day = diff / (24 * 60 * 60 * 1000); 
            hour = (diff / (60 * 60 * 1000) - day * 24); 
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60); 
            sec = (diff/1000-day*24*60*60-hour*60*60-min*60); 
            mydate.setDay(day) ; 
            mydate.setHour(hour) ; 
            mydate.setMin(min) ; 
            mydate.setSec(sec) ; 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
        return mydate ; 
    }  
	
}
